/**
 * ------------------------------------------------------
 *  axios请求/响应拦截器的封装处理
 * ------------------------------------------------------
 *
 * Note: .
 */
import router from "@/router"
import axios from "axios"
import { getToken, removeToken } from "./token"
import { API_TIMEOUT, DATA_API } from "@/config/constants"

const requestAxios = axios.create({
  baseURL: DATA_API,  
  timeout: API_TIMEOUT
})

/**
 * 添加请求拦截器
 * 获取token，在请求头中注入token
 */
requestAxios.interceptors.request.use((config) => {
  const token = getToken()
  if(token){
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

/**
 * 添加响应拦截器
 */
requestAxios.interceptors.response.use((response) => {
  //接口正常响应
  return response.data
}, (error) => {
  // 超出 2xx 范围的状态码都会触发该函数。
  //监控401 token失效，跳转到登录页
  if(error.response.status ===401){
    removeToken()
    router.navigate('/login')
    window.location.reload()
  }
  return Promise.reject(error)
})

export { requestAxios }
